//
//  GoEasyMessageDecoder.swift
//  uwantgoeasy
//
//  Created by 冯传宝 on 12/11/15.
//  Copyright © 2015 uwantsoft. All rights reserved.
//

import Foundation
class GoEasyMessageDecoder{
    
    func decode(msg:[UInt8])->ServerMessage{
        let totalLength = msg.count
        let data:NSData = NSData(bytes: msg, length: totalLength)
        var subTypeBytes:[UInt8] = [UInt8](count: 4, repeatedValue: 0)
        data.getBytes(&subTypeBytes, length: 4)
        
        var contentBytes:[UInt8] = [UInt8](count: totalLength-4, repeatedValue: 0)
        data.getBytes(&contentBytes, range: NSMakeRange(4,totalLength-4))
        
        let contentStr = String(bytes: contentBytes, encoding: NSUTF8StringEncoding)
        let decodedData = NSData(base64EncodedString: contentStr!, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
        let json = GoEasyJsonUtils.dataAsDict(decodedData!)
        let typeCode = Int32(subTypeBytes[3])
        
        var serverMessage:ServerMessage?
        switch typeCode{
        case GoEasyServerMessageType.AUTHORIZE_RESULT.rawValue:
            serverMessage = AuthorizeResult(json:json)
        case GoEasyServerMessageType.SUBSCRIBE_RESULT.rawValue:
            serverMessage = SubscribeResult(json:json)
        case GoEasyServerMessageType.PUBLISH_RESULT.rawValue:
            serverMessage = PublishResult(json:json)
        case GoEasyServerMessageType.PUSH.rawValue:
            serverMessage = Push(json:json)
        case GoEasyServerMessageType.UNSUBSCRIBE_RESULT.rawValue:
            serverMessage = UnsubscribeResult(json:json)
        default:
            print("Unknow message type code:\(typeCode)")
        }
        return serverMessage!
    }
}